﻿//---------------------------------------------------------------------
// <copyright file="UnityControllerFactory.cs" company="Travis Merkel">
//      Copyright (c) Travis Merkel. All Rights Reserved.
//      Information Contained Herein is Proprietary and Confidential.
// </copyright>
// <summary>
// Controller factory that uses a UnityContainer to register/retrieve information
// about controllers and their dependencies.
// </summary>
// <author>tmerkel</author>
//---------------------------------------------------------------------
namespace RecipeBook.UI.Web
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.Practices.Unity;

    /// <summary>
    /// Controller factory that uses a UnityContainer to register/retrieve information
    /// about controllers and their dependencies.
    /// </summary>
    public class UnityControllerFactory : DefaultControllerFactory
    {
        IUnityContainer container;

        /// <summary>
        /// Initializes a new instance of the UnityControllerFactory class.
        /// </summary>
        /// <param name="container">IUnityContainer instance to use to resolve dependencies in the project.</param>
        public UnityControllerFactory(IUnityContainer container)
        {
            this.container = container;
        }

        /// <summary>
        /// Retrieves the controller instance by using the specified type.
        /// </summary>
        /// <param name="requestContext">Context of the request.</param>
        /// <param name="controllerType">The type of the controller.</param>
        /// <returns>An instance of the controller.</returns>
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                {
                    throw new ArgumentNullException("controllerType");
                }

                if (!typeof(IController).IsAssignableFrom(controllerType))
                {
                    throw new ArgumentException(string.Format(
                           "Type requested is not a controller: {0}",
                           controllerType.Name),
                           "controllerType");
                }

                return container.Resolve(controllerType) as IController;
            }
            catch
            {
                return null; 
            }
        }
    }
}